import 'package:flutter/services.dart';
import 'package:flutter_deer/index/iview/indicator_document_list_iview.dart';
import 'package:flutter_deer/index/presenter/indicator_document_list_presenter.dart';
import 'package:flutter_deer/index/provider/indicator_document_list_page_provider.dart';
import 'package:flutter_deer/mvp/base_page.dart';
import 'package:flutter_deer/mvp/power_presenter.dart';
import 'package:flutter/material.dart';
import 'package:flutter_deer/res/constant.dart';
import 'package:flutter_deer/res/resources.dart';
import 'package:flutter_deer/util/other_utils.dart';
import 'package:flutter_deer/util/screen_utils.dart';
import 'package:flutter_deer/util/theme_utils.dart';
import 'package:flutter_deer/index/models/indicator_document_entity.dart';
import 'package:flutter_deer/widgets/fadein_text.dart';
import 'package:flutter_deer/widgets/my_refresh_list.dart';
import 'package:horizontal_data_table/horizontal_data_table.dart';
import 'package:flutter_deer/widgets/state_layout.dart';
import 'package:flutter_gen/gen_l10n/deer_localizations.dart';
import 'package:lottie/lottie.dart';
import 'package:provider/provider.dart';

class IndicatorDocumentPage extends StatefulWidget {
  const IndicatorDocumentPage({super.key});

  @override
  _IndicatorDocumentPageState createState() => _IndicatorDocumentPageState();
}

class _IndicatorDocumentPageState extends State<IndicatorDocumentPage>
    with
        BasePageMixin<IndicatorDocumentPage, PowerPresenter>,
        TickerProviderStateMixin
    implements IndicatorDocumentListIMvpView {
  final GlobalKey _bodyKey = GlobalKey();
  final HDTRefreshController _hdtRefreshController = HDTRefreshController();
  late IndicatorDocumentListPagePresenter indicatorDocumentListPagePresenter;
  IndicatorDocumentListPageProvider provider =
      IndicatorDocumentListPageProvider();
  @override
  PowerPresenter<dynamic> createPresenter() {
    final PowerPresenter<dynamic> powerPresenter =
        PowerPresenter<dynamic>(this);
    indicatorDocumentListPagePresenter =
        new IndicatorDocumentListPagePresenter();
    powerPresenter.requestPresenter([indicatorDocumentListPagePresenter]);
    return powerPresenter;
  }

  @override
  void setIndicatorDocumentPage(IndicatorDocumentPageEntity? pageEntity) {
    provider.setIndicatorDocumentItemPage(pageEntity);
  }

  @override
  void initState() {
    super.initState();
    // 强制横屏
    SystemChrome.setPreferredOrientations(
        [DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]);
    if (mounted) {
      _onRefresh();
    }
  }

  @override
  void dispose() {
    // provider.dispose();
    super.dispose();
    // 强制竖屏
    SystemChrome.setPreferredOrientations(
        [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
  }

  @override
  Widget build(BuildContext context) {
    final Color? iconColor = ThemeUtils.getIconColor(context);
    return ChangeNotifierProvider<IndicatorDocumentListPageProvider>(
        create: (_) => provider,
        child: Consumer<IndicatorDocumentListPageProvider>(
            builder: (_, provider, child) {
          if (provider.stateType == StateType.loading) {
            return Scaffold(
              key: _bodyKey,
              appBar: AppBar(
                  leading: IconButton(
                    onPressed: () async {
                      FocusManager.instance.primaryFocus?.unfocus();
                      final isBack = await Navigator.maybePop(context);
                      if (!isBack) {
                        await SystemNavigator.pop();
                      }
                    },
                    tooltip: '${DeerLocalizations.of(context)!.back.nullSafe}',
                    padding: EdgeInsets.all(12.0),
                    icon: Image.asset(
                      Constant.backImg,
                      color: ThemeUtils.getIconColor(context),
                      height: 24,
                      width: 24,
                    ),
                  ),
                  title: Text('指标单据',
                      style: TextStyle(
                        fontSize: Dimens.font_sp18,
                        color:
                            context.isDark ? Colours.text_gray : Colours.text,
                      )),
                  actions: <Widget>[]),
              body: StateLayout(type: StateType.loading),
            );
          }
          return Scaffold(
              key: _bodyKey,
              appBar: AppBar(
                  leading: IconButton(
                    onPressed: () async {
                      FocusManager.instance.primaryFocus?.unfocus();
                      final isBack = await Navigator.maybePop(context);
                      if (!isBack) {
                        await SystemNavigator.pop();
                      }
                    },
                    tooltip: '${DeerLocalizations.of(context)!.back.nullSafe}',
                    padding: EdgeInsets.all(12.0),
                    icon: Image.asset(
                      Constant.backImg,
                      color: ThemeUtils.getIconColor(context),
                      height: 24,
                      width: 24,
                    ),
                  ),
                  title: Text('指标单据',
                      style: TextStyle(
                        fontSize: Dimens.font_sp18,
                        color:
                            context.isDark ? Colours.text_gray : Colours.text,
                      )),
                  actions: <Widget>[]),
              body: provider.list!.length > 0
                  ? getDeerListView(provider)
                  : Container(
                      width: MediaQuery.of(context).size.width,
                      child: Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Lottie.asset('assets/lottie/no_football_game.json',
                                width: MediaQuery.of(context).size.width / 3,
                                fit: BoxFit.cover),
                            Gaps.vGap8,
                            FadeInText(
                                text:
                                    '${DeerLocalizations.of(context)!.noGame.nullSafe}')
                          ],
                        ),
                      ),
                    ));
        }));
  }

  HorizontalDataTable getDeerListView(
      IndicatorDocumentListPageProvider provider) {
    int leftHeadCount = 1;
    List<String> headers = [
      '预算年度',
      '业务主管处室',
      '财政区划',
      '本级指标文号',
      '指标余额',
      '指标文标题',
      '发文时间',
      '指标说明',
      '政府支出经济分类',
      '预算次级',
      '指标可执行标志',
      '上级指标文号',
      '项目名称',
      '单位名称',
      '指标金额',
      '资金来源',
      '调剂资金',
      '是否调剂',
      '是否专项债指标'
    ];
    List<String> columns = [
      'FISCAL_YEAR',
      'MANAGE_MOF_DEP_NAME',
      'MOF_DIV_CODE',
      'COR_BGT_DOC_NO',
      'CUR_AMT',
      'BGT_DOC_TITLE',
      'DOC_DATE',
      'BGT_DEC',
      'GOV_BGT_ECO_NAME',
      'BUDGET_LEVEL_NAME',
      'BGT_EXE_FLAG',
      'SUP_BGT_DOC_NO',
      'PRO_NAME',
      'AGENCY_NAME',
      'AMOUNT',
      'SOURCE_TYPE_NAME',
      'DIS_AMT',
      'is_dis',
      'is_special'
    ];
    List<Container> headContainers = [];
    List<double> rightWidths = [];
    List<double> leftWidths = [];
    double rightWidth = 0;
    double leftWidth = 0;
    for (int i = 0; i < headers.length; i++) {
      double headWidth = Screen.calculateTextWidth(
              context, headers.elementAt(i), FontWeight.bold, 12, 300, 1) +
          10;
      if (i < leftHeadCount) {
        leftWidth += headWidth;
        leftWidths.add(headWidth);
      } else {
        rightWidth += headWidth;
        rightWidths.add(headWidth);
      }
      headContainers.add(Container(
        width: headWidth,
        height: 56,
        padding: const EdgeInsets.fromLTRB(0, 0, 0, 0),
        alignment: Alignment.centerLeft,
        child: Text(headers.elementAt(i),
            style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 12)),
      ));
    }
    return HorizontalDataTable(
      leftHandSideColumnWidth: leftWidth,
      rightHandSideColumnWidth: rightWidth,
      isFixedFooter: false,
      isFixedHeader: true,
      headerWidgets: headContainers,
      footerWidgets: headContainers,
      leftHandSideColBackgroundColor: const Color(0xFFFFFFFF),
      rightHandSideColBackgroundColor: const Color(0xFFFFFFFF),
      enablePullToRefresh: true,
      refreshIndicator: const WaterDropHeader(),
      enablePullToLoadNewData: true,
      loadIndicator: const ClassicFooter(),
      htdRefreshController: _hdtRefreshController,
      onLoad: _loadMore,
      onRefresh: _onRefresh,
      rowSeparatorWidget: const Divider(
        color: Colors.black38,
        height: 1.0,
        thickness: 0.0,
      ),
      itemCount: provider.list!.length,
      leftSideItemBuilder: (context, index) {
        IndicatorDocumentEntity doc = provider.list!.elementAt(index);
        List<Container> cells = [];
        for (int i = 0; i < leftWidths.length; i++) {
          cells.add(Container(
            width: leftWidths.elementAt(i),
            height: 52,
            padding: const EdgeInsets.fromLTRB(5, 0, 0, 0),
            alignment: Alignment.center,
            child: Text(
              doc.toJson()[columns.elementAt(i)].toString(),
              style: TextStyle(fontSize: 10),
            ),
          ));
        }
        return Row(
          children: cells,
        );
      },
      rightSideItemBuilder: (context, index) {
        IndicatorDocumentEntity doc = provider.list!.elementAt(index);
        List<Container> cells = [];
        for (int i = 0; i < rightWidths.length; i++) {
          cells.add(Container(
            width: rightWidths.elementAt(i),
            height: 52,
            padding: const EdgeInsets.fromLTRB(5, 0, 0, 0),
            alignment: Alignment.center,
            child: Text(
              doc.toJson()[columns[leftHeadCount + i]].toString(),
              style: TextStyle(fontSize: 10),
            ),
          ));
        }
        return Row(
          children: cells,
        );
      },
    );
  }

  Future<dynamic> _onRefresh() async {
    Future.delayed(Duration(seconds: 1), () {
      indicatorDocumentListPagePresenter.getIndicatorDocumentList('2022');
      _hdtRefreshController.loadComplete();
    });
  }

  Future<dynamic> _loadMore() async {
    Future.delayed(Duration(seconds: 1), () {
      indicatorDocumentListPagePresenter.getMoreIndentList(
          '2022', provider.currentPage! + 1);
      _hdtRefreshController.refreshCompleted();
    });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }

  @override
  bool get wantKeepAlive => false;
}
